/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.cux.workflow.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.redragon.framework.springmvc.ControllerSupport;
import org.apache.commons.lang.StringUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.JsonUtil;

import com.erp.cux.workflow.dao.model.CuxWorkflowConfHead;
import com.erp.cux.workflow.dao.model.CuxWorkflowConfLine;
import com.erp.cux.workflow.dao.model.CuxWorkflowRecord;
import com.erp.cux.workflow.dao.model.CuxWorkflowRecordCO;
import com.erp.cux.workflow.service.CuxWorkflowConfHeadService;
import com.erp.cux.workflow.service.CuxWorkflowConfLineService;
import com.erp.cux.workflow.service.CuxWorkflowRecordService;
import com.erp.hr.dao.model.HrDepartment;
import com.erp.hr.dao.model.HrStaff;
import com.erp.hr.dao.model.HrStaffDepartmentR;
import com.erp.hr.dao.model.HrStaffDepartmentRCO;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.hr.service.HrStaffDepartmentRService;
import com.erp.hr.service.HrStaffService;

@Controller
@RequestMapping("/web/cuxWorkflowRecord")
public class CuxWorkflowRecordWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(CuxWorkflowRecordWebController.class);
    
    //服务层注入
    @Autowired
    private CuxWorkflowRecordService cuxWorkflowRecordService;
    @Autowired
    private CuxWorkflowConfHeadService cuxWorkflowConfHeadService;
    @Autowired
    private CuxWorkflowConfLineService cuxWorkflowConfLineService;
    @Autowired
    private HrStaffDepartmentRService hrStaffDepartmentRService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private HrStaffService hrStaffService;
    
    @Override
    public String getExceptionRedirectUrl() {
        // TODO Auto-generated method stub
        return null;
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2021-03-02 14:05:26
     * @author 
     * @param pages
     * @param cuxWorkflowRecordCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getCuxWorkflowRecordList")
    public String getCuxWorkflowRecordList(Pages pages, CuxWorkflowRecordCO cuxWorkflowRecordCO, Model model) {
        //TODO: 分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(10);
        pages.setShowPageNum(7);
        pages.setStartEndPageNum(2);
        
        //分页查询数据
        List<CuxWorkflowRecord> cuxWorkflowRecordList = this.cuxWorkflowRecordService.getDataObjects(pages, cuxWorkflowRecordCO);
        
        //页面属性设置
        model.addAttribute("cuxWorkflowRecordList", cuxWorkflowRecordList);
        model.addAttribute("pages", pages);
        
        return "cuxWorkflowRecord/cuxWorkflowRecordList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2021-03-02 14:05:26
     * @author 
     * @param cuxWorkflowRecord
     * @param model
     * @return String
     *
     */
    @RequestMapping("getCuxWorkflowRecord")
    public String getCuxWorkflowRecord(CuxWorkflowRecord cuxWorkflowRecord, Model model) {
        //TODO: 查询要编辑的数据
        
        //页面属性设置
        model.addAttribute("cuxWorkflowRecord", cuxWorkflowRecord);
        
        return "cuxWorkflowRecord/cuxWorkflowRecordEdit";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2021-03-02 14:05:26
     * @author 
     * @param cuxWorkflowRecord
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editCuxWorkflowRecord")
    @ResponseBody
    public String editCuxWorkflowRecord(@Valid CuxWorkflowRecord cuxWorkflowRecord, String submitFlag, String approveFlag, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        String callback = "";
        
        try {
            //对当前编辑的对象初始化默认的字段
            if(cuxWorkflowRecord.getRecordId()==null) {
                cuxWorkflowRecord.setRecordCode(SnowFlake.getConcurrentId().toString());
            }
            
            if(submitFlag.contentEquals("Y")) {
                //获取当前节点,判定当前单据是否已经提交审批，不能重复提交
                CuxWorkflowRecord currentRecord = this.cuxWorkflowRecordService.getCurrentRecordByBill(cuxWorkflowRecord.getBillType(), cuxWorkflowRecord.getBillHeadCode());
                if(currentRecord!=null&&currentRecord.getConfHeadCode().contentEquals(cuxWorkflowRecord.getConfHeadCode())&&currentRecord.getConfLineCode().contentEquals(cuxWorkflowRecord.getConfLineCode())) {
                }else {
                    //保存编辑的数据
                    this.cuxWorkflowRecordService.insertOrUpdateDataObject(cuxWorkflowRecord);
                }
                //如果是提交单据
                callback = "submit";
            }else {
                if(approveFlag.contentEquals("Y")) {
                    //如果是审批单据
                    if(cuxWorkflowRecord.getApprovePerson().contentEquals("finishStaffCode")) {
                        //如果最后节点，获取当前节点并更新
                        CuxWorkflowRecord currentRecord = this.cuxWorkflowRecordService.getCurrentRecordByBill(cuxWorkflowRecord.getBillType(), cuxWorkflowRecord.getBillHeadCode());
                        currentRecord.setApproveResult(cuxWorkflowRecord.getApproveResult());
                        currentRecord.setApproveComment(cuxWorkflowRecord.getApproveComment());
                        this.cuxWorkflowRecordService.updateDataObject(currentRecord);
                        
                        callback = "approved";
                    }else {
                        //如果中间节点，保存编辑的数据
                        this.cuxWorkflowRecordService.approveWorkflowRecode(cuxWorkflowRecord);
                    }
                }else {
                    //获取当前节点并更新
                    CuxWorkflowRecord currentRecord = this.cuxWorkflowRecordService.getCurrentRecordByBill(cuxWorkflowRecord.getBillType(), cuxWorkflowRecord.getBillHeadCode());
                    currentRecord.setApproveResult(cuxWorkflowRecord.getApproveResult());
                    currentRecord.setApproveComment(cuxWorkflowRecord.getApproveComment());
                    this.cuxWorkflowRecordService.updateDataObject(currentRecord);
                    
                    //如果是驳回单据
                    callback = "reject";
                }
            }
            
            return "{\"result\":\"success\", \"callback\": \""+callback+"\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\", \"callback\": \""+callback+"\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2021-03-02 14:05:26
     * @author 
     * @param cuxWorkflowRecord
     * @return String
     *
     */
    @RequestMapping("deleteCuxWorkflowRecord")
    public String deleteCuxWorkflowRecord(CuxWorkflowRecord cuxWorkflowRecord, RedirectAttributes attr) {
        //TODO: 删除数据前验证数据
        
        //删除数据
        this.cuxWorkflowRecordService.deleteDataObject(cuxWorkflowRecord);
        //提示信息
        attr.addFlashAttribute("hint", "success");
        
        return "redirect:getCuxWorkflowRecordList";
    }
    
    
    
    /**
     * 
     * @description 获取工作流审批弹性
     * @date 2021年3月2日
     * @author dongbin
     * @param model
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("getApproveWorkflowModal")
    public String getApproveWorkflowModal(String billType, String billHeadCode, String billDepartmentCode, String submitFlag, String approveFlag, Model model, RedirectAttributes attr) {
        //判断是提交还是审批
        if(submitFlag.contentEquals("Y")) {
            //获取单据对应的工作流
            CuxWorkflowConfHead cuxWorkflowConfHead = this.cuxWorkflowConfHeadService.getCuxWorkflowConfHeadByBusinessType(billType);
            //获取工作流的第一个节点
            CuxWorkflowConfLine cuxWorkflowConfLine = this.cuxWorkflowConfLineService.getFirstTaskByWorkflow(cuxWorkflowConfHead.getConfHeadCode());
            
            //页面属性设置
            model.addAttribute("confHeadCode", cuxWorkflowConfLine.getConfHeadCode());
            model.addAttribute("confLineCode", cuxWorkflowConfLine.getConfLineCode());
            model.addAttribute("approvePersonMap", this.getApprovePerson(cuxWorkflowConfLine, billDepartmentCode));
        }else {
            //判断是通过还是驳回
            if(approveFlag.contentEquals("Y")) {
                //获取工作流当前记录
                CuxWorkflowRecord cuxWorkflowRecord = this.cuxWorkflowRecordService.getCurrentRecordByBill(billType, billHeadCode);
                //获取工作流的下一节点
                Map<String, Object> params = new HashMap<String, Object>();
                CuxWorkflowConfLine cuxWorkflowConfLine = this.cuxWorkflowConfLineService.getNextTaskByTaskCode(cuxWorkflowRecord.getConfHeadCode(), cuxWorkflowRecord.getConfLineCode(), params);
                
                //页面属性设置
                if(cuxWorkflowConfLine!=null) {
                    model.addAttribute("confHeadCode", cuxWorkflowConfLine.getConfHeadCode());
                    model.addAttribute("confLineCode", cuxWorkflowConfLine.getConfLineCode());
                    model.addAttribute("approvePersonMap", this.getApprovePerson(cuxWorkflowConfLine, billDepartmentCode));
                }else {
                    model.addAttribute("confHeadCode", "null");
                    model.addAttribute("confLineCode", "null");
                    
                    Map<String, String> approvePersonMap = new HashMap<String, String>();
                    approvePersonMap.put("finishStaffCode", "流程结束");
                    model.addAttribute("approvePersonMap", approvePersonMap);
                }
                
            }else {
                //驳回到上一节点
                //CuxWorkflowRecord cuxWorkflowRecord = this.cuxWorkflowRecordService.getLastRecordByBill(billType, billHeadCode);
                //Map<String, String> approvePersonMap = new HashMap<String, String>();
                //HrStaff hrStaff = this.hrCommonService.getHrStaff(cuxWorkflowRecord.getApprovePerson());
                //HrStaffInfoRO hrStaffInfoRO = this.hrCommonService.getStaffInfo(hrStaff.getUsername());
                //approvePersonMap.put(cuxWorkflowRecord.getApprovePerson(), hrStaffInfoRO.getStaffName()+"-"+hrStaffInfoRO.getDepartmentSegmentDesc());
                //model.addAttribute("confHeadCode", cuxWorkflowRecord.getConfHeadCode());
                //model.addAttribute("confLineCode", cuxWorkflowRecord.getConfLineCode());
                //model.addAttribute("approvePersonMap", approvePersonMap);
                
                //驳回到提交人
                Map<String, String> approvePersonMap = new HashMap<String, String>();
                approvePersonMap.put("submitStaffCode", "提交人");
                
                //页面属性设置
                model.addAttribute("confHeadCode", "null");
                model.addAttribute("confLineCode", "null");
                model.addAttribute("approvePersonMap", approvePersonMap);
            }
                
            
        }

        
        return "common/workflow/approveWorkflow";
    }
    
    private Map<String, String> getApprovePerson(CuxWorkflowConfLine cuxWorkflowConfLine, String billDepartmentCode){
        //判断是否设置审批人
        Map<String, String> approvePersonMap = new HashMap<String, String>();
        
        if(StringUtils.isNotBlank(cuxWorkflowConfLine.getApprovePerson())) {
            try {
                HrStaff hrStaff = this.hrCommonService.getHrStaff(cuxWorkflowConfLine.getApprovePerson());
                HrStaffInfoRO hrStaffInfoRO = this.hrCommonService.getStaffInfo(hrStaff.getUsername());
                approvePersonMap.put(cuxWorkflowConfLine.getApprovePerson(), hrStaffInfoRO.getStaffName()+"-"+hrStaffInfoRO.getDepartmentSegmentDesc());
            }catch(Exception e) {}
        } else if(StringUtils.isNotBlank(cuxWorkflowConfLine.getApproveDepartment())&&StringUtils.isNotBlank(cuxWorkflowConfLine.getApprovePosition())) {
            //真实部门编码
            String realApproveDepartment = cuxWorkflowConfLine.getApproveDepartment();
            //判断真实部门还是逻辑部门
            //获取部门信息
            HrDepartment hrDepartment = this.hrCommonService.getHrDepartment(billDepartmentCode);
            if(cuxWorkflowConfLine.getApproveDepartment().contentEquals("sys_wf_department0")) {
                realApproveDepartment = hrDepartment.getDepartmentCode();
            }else if(cuxWorkflowConfLine.getApproveDepartment().contentEquals("sys_wf_department1")) {
                String[] segments = hrDepartment.getSegmentCode().split("_");
                if(segments.length-2>=0) {
                    realApproveDepartment = segments[segments.length-2];
                }else {
                    realApproveDepartment = hrDepartment.getDepartmentCode();
                }
            }else if(cuxWorkflowConfLine.getApproveDepartment().contentEquals("sys_wf_department2")) {
                String[] segments = hrDepartment.getSegmentCode().split("_");
                if(segments.length-3>=0) {
                    realApproveDepartment = segments[segments.length-3];
                }else {
                    realApproveDepartment = hrDepartment.getDepartmentCode();
                }
            }
            
            //获取部门和岗位对应的职员
            HrStaffDepartmentRCO hrStaffDepartmentRCO = new HrStaffDepartmentRCO();
            hrStaffDepartmentRCO.setDepartmentCode(realApproveDepartment);
            hrStaffDepartmentRCO.setPositionCode(cuxWorkflowConfLine.getApprovePosition());
            List<HrStaffDepartmentR> hrStaffDepartmentRList = this.hrStaffDepartmentRService.getDataObjects(hrStaffDepartmentRCO);
            //循环获取职员信息
            for(HrStaffDepartmentR hrStaffDepartmentR: hrStaffDepartmentRList) {
                try {
                    HrStaff hrStaff = this.hrCommonService.getHrStaff(hrStaffDepartmentR.getStaffCode());
                    HrStaffInfoRO hrStaffInfoRO = this.hrCommonService.getStaffInfo(hrStaff.getUsername());
                    approvePersonMap.put(hrStaffInfoRO.getStaffCode(), hrStaffInfoRO.getStaffName()+"-"+hrStaffInfoRO.getDepartmentSegmentDesc());
                }catch(Exception e) {}
            }
        }
        
        return approvePersonMap;
    }
    
    
    
    @RequestMapping("getWorkflowRecordListModal")
    public String getWorkflowRecordListModal(String billType, String billHeadCode, Model model, RedirectAttributes attr) {
        if(StringUtils.isNotBlank(billType)&&StringUtils.isNotBlank(billHeadCode)) {
            //获取单据所有审批记录
            CuxWorkflowRecordCO cuxWorkflowRecordCO = new CuxWorkflowRecordCO();
            cuxWorkflowRecordCO.setBillType(billType);
            cuxWorkflowRecordCO.setBillHeadCode(billHeadCode);
            List<CuxWorkflowRecord> cuxWorkflowRecordList = this.cuxWorkflowRecordService.getDataObjects(cuxWorkflowRecordCO);
            //循环获取审批信息
            for(CuxWorkflowRecord cuxWorkflowRecord: cuxWorkflowRecordList) {
                cuxWorkflowRecord.setTaskName(this.cuxWorkflowConfLineService.getDataObject(cuxWorkflowRecord.getConfLineCode()).getTaskName());
                //获取职员信息
                HrStaffInfoRO hrStaffInfoRO = this.hrCommonService.getStaffInfo(this.hrStaffService.getUsernameByStaffCode(cuxWorkflowRecord.getApprovePerson()));
                cuxWorkflowRecord.setApprovePersonName(hrStaffInfoRO.getStaffName());
                cuxWorkflowRecord.setApprovePersonDepartment(hrStaffInfoRO.getDepartmentSegmentDesc());
                cuxWorkflowRecord.setApprovePersonPosition(hrStaffInfoRO.getPositionName());
            }
            
            //页面属性设置
            model.addAttribute("cuxWorkflowRecordList", cuxWorkflowRecordList);
        }
        
        return "common/workflow/workflowRecordList";
    }
}
